package com.hzk.rabbitmq;

import com.hzk.pojo.Order;
import com.hzk.pojo.SeckillMessage;
import com.hzk.pojo.SeckillOrder;
import com.hzk.pojo.UserBasic;
import com.hzk.service.IGoodsService;
import com.hzk.service.IOrderService;
import com.hzk.utils.JsonUtil;
import com.hzk.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author zhoubin
 * @since 1.0.0
 */
@Service
@Slf4j
public class MQReceiver {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String msg) {
        log.info("QUEUE接受消息：" + msg);
        SeckillMessage message = JsonUtil.jsonStr2Object(msg,
                SeckillMessage.class);
        Long goodsId = message.getGoodsId();
        UserBasic user = message.getUser();
        int money = message.getMoney();
        GoodsVo goods = goodsService.findGoodsByid(goodsId);
        //判断库存
        if (goods.getStockCount() < 1) {
            return;
            /*throw new GabalException(RespBeanEnum.NULLGOODS_ERROR);*/

        }
        //判断是否重复抢购
        // SeckillOrder seckillOrder = seckillOrderService.getOne(new
        //QueryWrapper<SeckillOrder>().eq("user_id",
        //    user.getId()).eq(
        //    "goods_id",
        //    goodsId));
        //判断秒杀订单里面有没有这条记录:直接在redis缓存里面去找
        SeckillOrder seckillOrderJson = (SeckillOrder)
                redisTemplate.opsForValue().get("seckillorder:" + user.getId() + ":" + goodsId);

        if (seckillOrderJson != null) {
            return;
            /*throw new GabalException(RespBeanEnum.RESECKILL_ERROR);*/
        }
        orderService.secKill(user, goods,money);
        log.info("成功！！");
    }
}
